package com.atguigu.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.PmsCategoryDao;
import com.atguigu.gulimall.product.entity.PmsCategoryEntity;
import com.atguigu.gulimall.product.service.PmsCategoryService;


@Service("pmsCategoryService")
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryDao, PmsCategoryEntity> implements PmsCategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsCategoryEntity> page = this.page(
                new Query<PmsCategoryEntity>().getPage(params),
                new QueryWrapper<PmsCategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<PmsCategoryEntity> listWithTree() {
        List<PmsCategoryEntity> categoryEntities = this.baseMapper.selectList(null);
        // 获取所有的一级分类
        List<PmsCategoryEntity> level1Category =
                categoryEntities.stream().filter(category -> category.getParentCid() == 0).collect(Collectors.toList());

        // 为一级分类设置子分类
        List<PmsCategoryEntity> result = level1Category.stream().map(category -> {
             category.setChildren(getCategoryChildren(category, categoryEntities));
             return category;
        }).sorted((c1,c2) -> (c1.getSort() == null?0:c1.getSort()) - (c2.getSort() == null?0:c2.getSort())).collect(Collectors.toList());

        return result;
    }

    // 找到root的子分类
    private List<PmsCategoryEntity> getCategoryChildren(PmsCategoryEntity root, List<PmsCategoryEntity> categoryEntities) {
        return categoryEntities.stream().filter(category -> category.getParentCid().equals(root.getCatId())) // root的子分类
                .map(category -> {
                    category.setChildren(getCategoryChildren(category, categoryEntities));
                    return category;
                })// 设置root的子分类的子分类
                .sorted((c1,c2) -> (c1.getSort() == null?0:c1.getSort()) - (c2.getSort() == null?0:c2.getSort())) // 排序
                .collect(Collectors.toList());
    }
}